package net.fdukedom.chart.constraints;

import net.fdukedom.chart.Function2D;

/**
 * 
 * Constraint of type <code>function</code> == 0.
 * 
 * @author Fedor Tsarev
 */
public class EqualsZeroConstraint extends Constraint {

	private final NonNegativeConstraint nonNegativeConstraint;
	
	private final int[] dx = new int[] {1, -1,  0, 0};
	private final int[] dy = new int[] {0,  0, -1, 1};
	
	public EqualsZeroConstraint(Function2D function) {
		super(function);
		nonNegativeConstraint = new NonNegativeConstraint(function);
	}

	@Override
	public boolean[][] getContainsMap(int width, int height, double minX, double minY, double maxX, double maxY) {
		boolean[][] tmp = nonNegativeConstraint.getContainsMap(width, height, minX, minY, maxX, maxY);
		
		// Only points lying on the border will be left.
		// An heuristical criteria is used to determine such
		// points: it must have neighbours belonging to the
		// area and neighbours not belonging to it
		
		// Cells are considered neigbours if they share
		// a side.
        boolean[][] res = new boolean[width][height];
		for (int i = 0; i < width; i++) {
			for (int j = 0; j < height; j++) {
				boolean hasArea = false;
				boolean hasNotArea = false;
				
				for (int k = 0; k < dx.length; k++) {
					int ni = i + dx[k];
					int nj = j + dy[k];
					if (0 <= ni && ni < width && 0 <= nj && nj < height) {
						if (tmp[ni][nj]) {
							hasArea = true;
						} else {
							hasNotArea = true;
						}
					}
				}
				
				if (hasArea && hasNotArea && tmp[i][j]) {
					res[i][j] = true;
				}
				
			}
		}
		
		return res;		
	}

}
